package com.yunji.common.utils;

import org.apache.commons.lang3.time.DateFormatUtils;

import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 时间工具类
 *
 * @author yunji
 */
public class TimeUtils extends org.apache.commons.lang3.time.DateUtils {
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    public static String YYYY_MM_DD_T_HH_MM_SS = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate() {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate() {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static String getTime() {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static String dateTimeNow() {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static String dateTimeNow(final String format) {
        return parseDateToStr(format, new Date());
    }

    public static String dateTime(final Date date) {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static String dateYmdHms(final Date date) {
        return parseDateToStr(YYYY_MM_DD_HH_MM_SS, date);
    }

    public static String parseDateToStr(final String format, final Date date) {
        if (date == null || format == null)
            return "";
        return new SimpleDateFormat(format).format(date);
    }

    public static Date dateTime(final String format, final String ts) {
        try {
            return new SimpleDateFormat(format).parse(ts);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static String datePath() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static String dateTime() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str) {
        if (str == null) {
            return null;
        }
        try {
            return parseDate(str.toString(), parsePatterns);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * @return String 带时区字符串
     * @Title zoneDate
     * @Desc 当前时间转换为字符串
     * @Date 2024-04-27 17:02:40.045
     */
    public static String zoneDate() {
        Date now = new Date();
        return DateFormatUtils.format(now, YYYY_MM_DD_T_HH_MM_SS);
    }

    /**
     * @param str 字符信息
     * @return Date 时间信息
     * @Title parseZoneDate
     * @Desc 字符串转换成时间
     * @Date 2024-04-27 17:02:06.259
     */
    public static Date parseZoneDate(String str) {
        if (str == null) {
            return null;
        }
        try {
            DateTimeFormatter formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
            ZonedDateTime zonedDateTime = ZonedDateTime.parse(str, formatter);
            return Date.from(zonedDateTime.toInstant());
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate() {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算相差天数
     */
    public static int differentDaysByMillisecond(Date date1, Date date2) {
        return differentByMillisecond(date1, date2, Calendar.DATE);
    }

    public static int differentByMillisecond(Date date1, Date date2, int type) {
        long time = 1000;
        switch (type) {
            case Calendar.MINUTE:
                time = time * 60;
                break;
            case Calendar.DATE:
                time = time * 60 * 60 * 24;
                break;
            case Calendar.HOUR:
                time = time * 60 * 60;
                break;
            case Calendar.YEAR:
                time = time * 60 * 60 * 24 * 365;
                break;
        }
        return Math.abs((int) ((date2.getTime() - date1.getTime()) / (time)));
    }

    /**
     * 计算时间差
     *
     * @param endDate   最后时间
     * @param startTime 开始时间
     * @return 时间差（天/小时/分钟）
     */
    public static Map<String, String> timeToMap(Date startTime, Date endDate) {

        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - startTime.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        long sec = diff % nd % nh % nm / ns;
        Map<String, String> map = new HashMap<String, String>();
        if (day > 0) {
            map.put("day", day + "天");
        }
        if (hour > 0) {
            map.put("hour", hour + "小时");
        }
        if (min > 0) {
            map.put("min", hour + "分钟");
        }
        if (min > 0) {
            map.put("sec", sec + "秒");
        }
        return map;
    }

    public static String time2Str(Date startTime, Date endDate) {
        Map<String, String> map = timeToMap(startTime, endDate);
        return StringUtils.null2Empty(map.get("day")) + StringUtils.null2Empty(map.get("hour")) + StringUtils.null2Empty(map.get("min")) + StringUtils.null2Empty(map.get("sec"));
    }

    /**
     * 增加 LocalDateTime ==> Date
     */
    public static Date toDate(LocalDateTime temporalAccessor) {
        ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * 增加 LocalDate ==> Date
     */
    public static Date toDate(LocalDate temporalAccessor) {
        LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0));
        ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * @param day 某天
     * @Title getMinDay
     * @Desc 获取某天最小时间段
     * @Date 2024-09-27 16:30:01.156
     * @Return LocalDateTime
     */
    public static LocalDateTime getMinDay(LocalDate day) {
        return LocalDateTime.of(LocalDate.from(day), LocalDateTime.MIN.toLocalTime());
    }

    /**
     * @param day 某天
     * @Title getMaxDay
     * @Desc 获取某天最大时间端
     * @Date 2024-09-27 16:30:22.468
     * @Return LocalDateTime
     */
    public static LocalDateTime getMaxDay(LocalDate day) {
        return LocalDateTime.of(LocalDate.from(day), LocalDateTime.MAX.toLocalTime());
    }

    /**
     * 获取次日00:00时间
     *
     * @return
     */
    public static Date getNextDate() {
        Calendar ca = Calendar.getInstance();
        ca.set(Calendar.HOUR_OF_DAY, 0);
        ca.set(Calendar.MINUTE, 0);
        ca.set(Calendar.SECOND, 0);
        ca.set(Calendar.MILLISECOND, 0);
        ca.add(Calendar.DAY_OF_MONTH, 1);
        return ca.getTime();
    }
}
